<template>
  <q-dialog 
    :model-value="modelValue" 
    @update:model-value="$emit('update:modelValue', $event)"
    class="create-group-dialog"
  >
    <q-card class="dialog-card wechat-style">
      <q-card-section class="dialog-header wechat-header">
        <div class="header-top">
          <q-input
            v-model="searchQuery"
            placeholder="搜索"
            outlined
            dense
            class="header-search"
            autocomplete="off"
            @update:model-value="handleSearch"
          >
            <template v-slot:prepend>
              <q-icon name="search" />
            </template>
          </q-input>
        </div>
        <div class="dialog-title">发起群聊</div>
        <div class="dialog-subtitle" v-if="selectedContacts.length > 0">
          已选择 {{ selectedContacts.length }} 个联系人
        </div>
        <div class="dialog-subtitle" v-else>
          未选择联系人
        </div>
      </q-card-section>
      <q-card-section class="dialog-body dialog-scrollable wechat-body">
        <div v-if="loadingFriends" class="loading-state">
          <q-spinner color="primary" size="2em" />
          <div class="loading-text">加载中...</div>
        </div>
        <div v-else-if="filteredFriends.length === 0" class="empty-state">
          <q-icon name="people_outline" size="48px" color="grey-4" />
          <div class="empty-text">暂无好友</div>
        </div>
        <div v-else class="contacts-list">
          <!-- 按字母分组显示 -->
          <template v-for="(group, letter) in groupedFriends" :key="letter">
            <div v-if="group.length > 0" class="letter-group">
              <div class="letter-separator">{{ letter }}</div>
              <div
                v-for="friend in group"
                :key="friend.to_id"
                class="contact-item"
                @click="toggleContact(friend)"
              >
                <div class="contact-avatar">
                  <img 
                    v-if="hasAvatar(friend) && !avatarErrors[friend.to_id] && cachedAvatarUrls[friend.to_id]" 
                    :src="cachedAvatarUrls[friend.to_id]"
                    class="avatar-image"
                    @error="handleAvatarError($event, friend)"
                  />
                  <img 
                    v-else
                    :src="getDefaultAvatarUrl(friend)"
                    class="avatar-image"
                  />
                </div>
                <div class="contact-info">
                  <div class="contact-name">{{ friend.remark || friend.user?.name || friend.to_id }}</div>
                </div>
                <div class="contact-checkbox">
                  <div 
                    class="contact-check"
                    :class="{ 'contact-check-selected': isSelected(friend) }"
                    @click.stop="toggleContact(friend)"
                  >
                    <q-icon 
                      v-if="isSelected(friend)"
                      name="check"
                      size="14px"
                      color="white"
                    />
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </q-card-section>
      <q-card-actions align="center" class="dialog-actions wechat-footer">
        <q-btn flat label="取消" @click="$emit('update:modelValue', false)" class="dialog-btn wechat-close-btn" />
        <q-btn
          flat
          label="创建"
          color="primary"
          @click="handleCreate"
          :loading="loading"
          :disable="selectedContacts.length === 0"
          class="dialog-btn wechat-btn wechat-btn-primary"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue'
import { getFriends, type ImFriendship } from '../services/im-friendship'
import { generateSquareDefaultAvatar } from '@/utils/avatar'
import { getCachedImageUrl } from '@/services/image-cache'
import { API_BASE_URL } from '@/config/env'
import { getUserAsync, getUser } from '../services/auth'

const props = defineProps<{
  modelValue: boolean
  loading?: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'create': [members: Array<{ id: string; name: string }>]
}>()

const searchQuery = ref('')
const friends = ref<ImFriendship[]>([])
const loadingFriends = ref(false)
const selectedContacts = ref<ImFriendship[]>([])
const avatarErrors = ref<Record<string, boolean>>({})
const cachedAvatarUrls = ref<Record<string, string>>({})
const currentUser = ref<any>(null)

// 检查是否是当前用户
const isCurrentUser = (friend: ImFriendship): boolean => {
  if (!currentUser.value) {
    return false
  }
  
  const user = currentUser.value
  const friendId = friend.to_id || friend.user?.open_id || friend.user?.id || ''
  const friendName = friend.user?.name || ''
  const friendOpenId = friend.user?.open_id || ''
  
  // 检查多种可能的ID匹配方式
  return friendId === (user.open_id || '') ||
         friendId === (user.id || '') ||
         friendId === (user.name || '') ||
         friendId === String(user.snowflake_id || '') ||
         friendName === (user.name || '') ||
         friendOpenId === (user.open_id || '')
}

// 过滤好友列表（排除当前用户）
const filteredFriends = computed(() => {
  // 先排除当前用户
  let filtered = friends.value.filter(friend => !isCurrentUser(friend))
  
  // 再根据搜索关键词过滤
  if (!searchQuery.value.trim()) {
    return filtered
  }
  const query = searchQuery.value.trim().toLowerCase()
  return filtered.filter(friend => {
    const name = (friend.remark || friend.user?.name || friend.to_id || '').toLowerCase()
    return name.includes(query)
  })
})

// 获取好友名称的首字母（用于分组）
const getFirstLetter = (friend: ImFriendship): string => {
  const name = friend.remark || friend.user?.name || friend.to_id || ''
  if (!name) return '#'
  
  const firstChar = name.trim()[0].toUpperCase()
  
  // 如果是中文字符
  if (/[\u4e00-\u9fa5]/.test(firstChar)) {
    return firstChar
  }
  
  // 如果是英文字母
  if (/[A-Z]/.test(firstChar)) {
    return firstChar
  }
  
  // 其他字符归为 #
  return '#'
}

// 按字母分组的好友列表
const groupedFriends = computed(() => {
  const groups: Record<string, ImFriendship[]> = {}
  
  filteredFriends.value.forEach(friend => {
    const letter = getFirstLetter(friend)
    if (!groups[letter]) {
      groups[letter] = []
    }
    groups[letter].push(friend)
  })
  
  // 对每个分组内的好友按名称排序
  Object.keys(groups).forEach(letter => {
    groups[letter].sort((a, b) => {
      const nameA = (a.remark || a.user?.name || a.to_id || '').toLowerCase()
      const nameB = (b.remark || b.user?.name || b.to_id || '').toLowerCase()
      return nameA.localeCompare(nameB, 'zh-CN')
    })
  })
  
  // 按字母顺序排序分组
  const sortedGroups: Record<string, ImFriendship[]> = {}
  const sortedLetters = Object.keys(groups).sort((a, b) => {
    if (a === '#') return 1
    if (b === '#') return -1
    return a.localeCompare(b)
  })
  
  sortedLetters.forEach(letter => {
    sortedGroups[letter] = groups[letter]
  })
  
  return sortedGroups
})

// 检查是否选中
const isSelected = (friend: ImFriendship): boolean => {
  return selectedContacts.value.some(f => f.to_id === friend.to_id)
}

// 切换选中状态
const toggleContact = (friend: ImFriendship) => {
  const index = selectedContacts.value.findIndex(f => f.to_id === friend.to_id)
  if (index >= 0) {
    selectedContacts.value.splice(index, 1)
  } else {
    selectedContacts.value.push(friend)
  }
}

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已在 computed 中处理
}

// 检查是否有头像
const hasAvatar = (friend: ImFriendship): boolean => {
  return !!(friend.user?.file_name)
}

// 获取默认头像URL
const getDefaultAvatarUrl = (friend: ImFriendship): string => {
  const userId = friend.to_id || friend.user?.open_id || friend.user?.id || ''
  const name = friend.remark || friend.user?.name || friend.to_id || ''
  return generateSquareDefaultAvatar(userId, name, 50, 4)
}

// 处理头像加载错误
const handleAvatarError = (event: Event, friend: ImFriendship) => {
  avatarErrors.value[friend.to_id] = true
}

// 加载好友头像
const loadFriendAvatar = async (friend: ImFriendship) => {
  if (!hasAvatar(friend)) {
    return
  }
  
  const friendId = friend.to_id
  if (cachedAvatarUrls.value[friendId]) {
    return
  }
  
  try {
    const url = `${API_BASE_URL}/api/upload/${friend.user!.file_name}`
    const cachedUrl = await getCachedImageUrl(url, true)
    if (cachedUrl) {
      cachedAvatarUrls.value[friendId] = cachedUrl
    } else {
      avatarErrors.value[friendId] = true
    }
  } catch (error) {
    console.warn(`加载好友 ${friendId} 的头像失败:`, error)
    avatarErrors.value[friendId] = true
  }
}

// 加载当前用户信息
const loadCurrentUser = async () => {
  try {
    currentUser.value = await getUserAsync()
    // 如果异步获取失败，尝试同步获取
    if (!currentUser.value) {
      currentUser.value = getUser()
    }
  } catch (error) {
    console.warn('获取当前用户信息失败:', error)
    // 尝试同步获取作为后备
    currentUser.value = getUser()
  }
}

// 加载好友列表
const loadFriends = async () => {
  loadingFriends.value = true
  try {
    // 先加载当前用户信息
    await loadCurrentUser()
    
    const friendsList = await getFriends(true)
    friends.value = friendsList
    
    // 加载头像
    for (const friend of friendsList) {
      if (hasAvatar(friend) && !cachedAvatarUrls.value[friend.to_id] && !avatarErrors.value[friend.to_id]) {
        await loadFriendAvatar(friend)
      }
    }
  } catch (error) {
    console.error('加载好友列表失败:', error)
  } finally {
    loadingFriends.value = false
  }
}

// 监听对话框打开/关闭
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    selectedContacts.value = []
    searchQuery.value = ''
    loadFriends()
  }
})

// 初始化时加载当前用户信息
onMounted(() => {
  loadCurrentUser()
})

// 验证选中的联系人都是好友
const validateFriends = (): boolean => {
  // 确保所有选中的联系人都在好友列表中
  const friendIds = new Set(friends.value.map(f => {
    return f.to_id || f.user?.open_id || f.user?.id || ''
  }))
  
  for (const contact of selectedContacts.value) {
    const contactId = contact.to_id || contact.user?.open_id || contact.user?.id || ''
    if (!friendIds.has(contactId)) {
      console.error('选中的联系人不是好友:', contactId)
      return false
    }
  }
  
  return true
}

// 处理创建
const handleCreate = () => {
  if (selectedContacts.value.length === 0) {
    return
  }
  
  // 验证所有选中的联系人都是好友（这是底线，非好友之间不能通信）
  if (!validateFriends()) {
    console.error('创建群组失败：选中的联系人中包含非好友用户')
    // 这里可以显示错误提示，但为了安全，我们直接返回
    return
  }
  
  // 提取选中的成员信息（ID 和名称）
  // 确保只使用好友的 open_id 或 to_id
  const members = selectedContacts.value.map(friend => {
    // 优先使用 open_id，如果没有则使用 to_id
    const id = friend.user?.open_id || friend.to_id
    const name = friend.remark || friend.user?.name || friend.to_id || ''
    
    // 再次验证：确保 ID 存在且是好友
    if (!id) {
      console.warn('好友信息不完整，跳过:', friend)
      return null
    }
    
    return { id, name }
  }).filter((m): m is { id: string; name: string } => m !== null && !!m.id)
  
  if (members.length === 0) {
    console.error('没有有效的成员可以添加到群组')
    return
  }
  
  emit('create', members)
}
</script>

<style lang="sass" scoped>
// 覆盖式对话框样式（不挤压原窗口）
.create-group-dialog
  :deep(.q-dialog__inner)
    justify-content: center !important
    align-items: center !important
    padding: 16px !important
    
  :deep(.q-dialog__backdrop)
    background: rgba(0, 0, 0, 0.5) !important
    backdrop-filter: blur(4px)

// 微信风格对话框
.wechat-style
  min-width: 480px
  max-width: 560px
  border-radius: 12px
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif
  overflow: hidden

.wechat-header
  background: #FFFFFF
  border-bottom: 1px solid #E5E5E5
  padding: 16px
  padding-bottom: 12px

.header-top
  margin-bottom: 12px

.header-search
  :deep(.q-field__control)
    border-radius: 4px
    border: 1px solid rgba(0, 0, 0, 0.1)
    background: #EDEDED
    height: 36px
    min-height: 36px
    padding: 0 12px
  
  :deep(.q-field--focused .q-field__control)
    background: #FFFFFF
    border-color: rgba(0, 0, 0, 0.15)
  
  :deep(.q-field__native)
    font-size: 14px
    color: #191919
  
  :deep(.q-icon)
    color: #666666

.dialog-title
  font-size: 17px
  font-weight: 500
  color: #191919
  line-height: 1.4
  margin-bottom: 4px
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.dialog-subtitle
  font-size: 14px
  color: #8E8E93
  font-weight: 400
  line-height: 1.4

.wechat-body
  background: #FFFFFF
  padding: 0
  max-height: 500px
  overflow-y: auto

.wechat-body::-webkit-scrollbar
  width: 6px

.wechat-body::-webkit-scrollbar-track
  background: transparent

.wechat-body::-webkit-scrollbar-thumb
  background: rgba(0, 0, 0, 0.2)
  border-radius: 3px

.wechat-body::-webkit-scrollbar-thumb:hover
  background: rgba(0, 0, 0, 0.3)

.loading-state
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  padding: 60px 24px
  text-align: center

.loading-text
  margin-top: 16px
  font-size: 14px
  color: #8E8E93

.empty-state
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  padding: 60px 24px
  text-align: center

.empty-text
  margin-top: 16px
  font-size: 14px
  color: #8E8E93

.contacts-list
  background: #FFFFFF

.letter-group
  width: 100%

.letter-separator
  padding: 5px 16px
  font-size: 13px
  font-weight: 400
  color: #8E8E93
  background: #F7F7F7
  border-bottom: 0.5px solid rgba(0, 0, 0, 0.08)
  letter-spacing: 0.5px

.contact-item
  display: flex
  align-items: center
  padding: 12px 16px
  cursor: pointer
  transition: background-color 0.15s ease
  background: #FFFFFF
  border-bottom: 0.5px solid rgba(0, 0, 0, 0.08)
  position: relative
  min-height: 74px

.contact-item:hover
  background: #F7F7F7

.contact-avatar
  width: 50px
  height: 50px
  flex-shrink: 0
  border-radius: 4px
  display: flex
  align-items: center
  justify-content: center
  overflow: hidden
  border: none
  margin-right: 14px
  background-size: cover
  background-position: center
  background-repeat: no-repeat
  position: relative
  background-color: transparent

.contact-avatar::after
  content: ''
  position: absolute
  top: 0
  left: 0
  right: 0
  bottom: 0
  border: 0.5px solid rgba(0, 0, 0, 0.08)
  border-radius: 4px
  pointer-events: none
  z-index: 1

.avatar-image
  width: 100%
  height: 100%
  object-fit: cover
  display: block
  position: relative
  z-index: 0

.contact-info
  flex: 1
  min-width: 0
  display: flex
  flex-direction: column
  justify-content: center

.contact-name
  font-weight: 400
  color: #191919
  font-size: 16px
  letter-spacing: 0
  line-height: 1.5
  overflow: hidden
  text-overflow: ellipsis
  white-space: nowrap

.contact-checkbox
  flex-shrink: 0
  margin-left: 12px

.contact-check
  width: 20px
  height: 20px
  border-radius: 50%
  border: 2px solid #C7C7CC
  background: #FFFFFF
  display: flex
  align-items: center
  justify-content: center
  cursor: pointer
  transition: all 0.2s ease
  flex-shrink: 0

.contact-check:hover
  border-color: #07C160

.contact-check-selected
  background: #07C160
  border-color: #07C160

.wechat-footer
  background: #FFFFFF
  border-top: 1px solid #E5E5E5
  padding: 12px 16px

.wechat-close-btn
  color: #576B95
  font-size: 16px
  font-weight: 400
  padding: 8px 16px
  min-width: auto

.wechat-close-btn:hover
  background: rgba(0, 0, 0, 0.05)

.wechat-btn
  min-width: 68px
  height: 32px
  padding: 0 16px
  font-size: 15px
  font-weight: 400
  border-radius: 4px
  text-transform: none
  box-shadow: none
  transition: background-color 0.2s ease
  border: none

.wechat-btn::before
  display: none

.wechat-btn:hover
  transform: none
  box-shadow: none

.wechat-btn:active
  transform: none
  box-shadow: none
  transition: background-color 0.1s ease

.wechat-btn-primary
  background: #FFFFFF
  color: #576B95
  font-weight: 500
  border: none

.wechat-btn-primary:hover
  background: #F5F5F5

.wechat-btn-primary:active
  background: #EDEDED

.wechat-btn-primary:disabled
  background: #C7C7CC
  color: #FFFFFF
  opacity: 0.6
</style>

